#include "mcp3421.h"
#include "i2c.h"


int MCP3421_Init(void)
{
    if(HAL_I2C_IsDeviceReady(&hi2c1,MCP3421ADDR,5,100) != HAL_OK)
    {
        return 0;
    }
    uint8_t parameter = 0x9d;  //系统参数配置为18位精度，自动转换模式，PGAx2增益。配置字见数据手册。
    HAL_I2C_Master_Transmit(&hi2c1,MCP3421ADDR,&parameter,1,100);
    HAL_Delay(10);
    while(HAL_I2C_IsDeviceReady(&hi2c1,MCP3421ADDR,5,100))
    {
        HAL_Delay(10);
    }
    return 1;
}


uint32_t MCP3421_Get_Value(void)
{
    uint32_t ADC_Value;
    uint8_t Adc_Temp[3]={0};
    if(HAL_I2C_IsDeviceReady(&hi2c1,MCP3421ADDR,5,100)==HAL_OK)
    {
        HAL_I2C_Master_Receive(&hi2c1,MCP3421ADDR,Adc_Temp,3,100);
        ADC_Value = Adc_Temp[0];
        ADC_Value&=0x03;
        ADC_Value<<=8;
        ADC_Value+= Adc_Temp[1];
        ADC_Value<<=8;
        ADC_Value+= Adc_Temp[2];
    }
    return  ADC_Value;
}


float MCP3421_Get_Voltage_mv(void)
{
    uint32_t Voltage;
    float Measure;
    Voltage = MCP3421_Get_Value();
    if((Voltage&0x00020000) == 0x00020000)      //判断最高位符号位是否为为1；为“1”则为负电压
    {
        Voltage&=0x0001ffff;
        Voltage=(~Voltage)+1;
        Voltage &=0x0001ffff;
        Measure = 15.625*Voltage;              //15.625为18位分辨率的精度。其他分辨率的精度见数据手册。
        Measure = Measure *0.001;
        return -Measure;
    }
    else                                    //为“0”则正电压直接转换
    {
        Voltage&=0x0001ffff;
        Measure = 15.625*Voltage;
        Measure = Measure *0.001;
        return Measure;
    }

}

//滑动窗口滤波
float MCP3421_get_voltage_glide_filter(void)
{
    #define FILTER_CUT 3
    static float filter_buf[FILTER_CUT];
    static uint16_t filter_cnt = 0;

    uint16_t i = 0;
    double sum = 0;


    filter_buf[filter_cnt] = MCP3421_Get_Voltage_mv() / 2;
    if(++filter_cnt >= FILTER_CUT)
    {
        filter_cnt = 0;
    }

    for(i = 0; i < FILTER_CUT; i++)
    {
        sum += filter_buf[i];
    }

    return (float)(sum/FILTER_CUT);

}
